<template>
  <el-affix :offset="0">
    <div class="navbar-container">
      <el-row :gutter="20" justify="space-between" align="middle" class="nav-row">
        <el-col :xs="12" :md="4">
          <div class="logo-wrapper">
            <img src="@/assets/logo.svg" alt="网站Logo" class="logo-img">
          </div>
        </el-col>

        <el-col :xs="12" :md="20" class="menu-col">
          <div class="desktop-menu-wrapper">
            <el-menu
              :default-active="activeIndex"
              mode="horizontal"
              :ellipsis="false"
              @select="handleSelect"
              class="desktop-menu"
            >
              <div class="flex-grow" />
              <template v-for="menu in menus" :key="menu.id">
                <el-sub-menu 
                  v-if="menu.children?.length" 
                  :index="menu.id"
                  :popper-class="'sub-menu-popper'"
                >
                  <template #title>
                    <el-icon v-if="menu.icon">
                      <component :is="getIconComponent(iconMap, menu.icon)" />
                    </el-icon>
                    <span>{{ menu.title }}</span>
                  </template>
                  <el-menu-item 
                    v-for="child in menu.children" 
                    :key="child.id" 
                    :index="child.id"
                    @click="navigateTo(child.path)"
                  >
                    {{ child.title }}
                  </el-menu-item>
                </el-sub-menu>
                <el-menu-item 
                  v-else 
                  :index="menu.id"
                  @click="navigateTo(menu.path)"
                >
                  <el-icon v-if="menu.icon">
                    <component :is="getIconComponent(iconMap, menu.icon)" />
                  </el-icon>
                  <span>{{ menu.title }}</span>
                </el-menu-item>
              </template>
            </el-menu>
          </div>

          <div class="hamburger-wrapper">
            <el-icon @click="isMobileMenuOpen = !isMobileMenuOpen">
              <component :is="isMobileMenuOpen ? Expand : Fold" />
            </el-icon>
          </div>
        </el-col>
      </el-row>

      <transition name="el-zoom-in-top">
        <div v-show="isMobileMenuOpen" class="mobile-menu-container">
          <el-menu
            :default-active="activeIndex"
            @select="handleSelect"
            class="mobile-menu"
          >
            <template v-for="menu in menus" :key="menu.id">
              <el-sub-menu v-if="menu.children?.length" :index="menu.id">
                <template #title>
                  <el-icon v-if="menu.icon">
                    <component :is="getIconComponent(iconMap, menu.icon)" />
                  </el-icon>
                  <span>{{ menu.title }}</span>
                </template>
                <el-menu-item 
                  v-for="child in menu.children" 
                  :key="child.id" 
                  :index="child.id"
                  @click="navigateTo(child.path)"
                >
                  {{ child.title }}
                </el-menu-item>
              </el-sub-menu>
              <el-menu-item 
                v-else 
                :index="menu.id"
                @click="navigateTo(menu.path)"
              >
                <el-icon v-if="menu.icon">
                  <component :is="getIconComponent(iconMap, menu.icon)" />
                </el-icon>
                <span>{{ menu.title }}</span>
              </el-menu-item>
            </template>
          </el-menu>
        </div>
      </transition>
    </div>
  </el-affix>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import type { Ref } from 'vue'
import {
  House,
  CopyDocument,
  Cpu,
  Fold,
  Expand,
  Notebook,
  Opportunity,
  Message
} from '@element-plus/icons-vue'
import type { Component } from 'vue'
import { getMenus } from '@/utils/api'
import type { MenuResponse, MenuItem } from '@/utils/api'
import { getIconComponent } from '@/utils'

const router = useRouter()
let activeIndex = ref<string>('')
let activeIndexBack = '' // 保存最近一次匹配的菜单ID
const isMobileMenuOpen = ref<boolean>(false)
const menus = ref<MenuItem[]>([])

// 路由路径到菜单 ID 的映射（用于初始化或 API 加载失败时的回退）
const pathToIdMap: Record<string, string> = {
  '/': '1',
  '/category': '2',
  '/icons': '3',
  '/show': '4',
  '/contact': '5',
  '/user': '6',
}

const handleSelect = (index: string) => {
  activeIndex.value = index
  isMobileMenuOpen.value = false
}

const navigateTo = (path: string, id?: string | number) => {
  if (path) {
    router.push(path)
  }
}

// 图标映射表
const iconMap: Record<string, Component> = {
  House,
  CopyDocument,
  Cpu,
  Notebook,
  Opportunity,
  Message,
}

// 根据当前路由路径，动态设置 activeIndex
const updateActiveIndex = () => {
  const currentPath = router.currentRoute.value.path
  activeIndexBack = activeIndex.value
  // 优先使用从 API 加载的菜单匹配
  if (menus.value.length > 0) {
    // 先尝试精确匹配
    const exactMatch = menus.value.find(menu => menu.path === currentPath)
    if (exactMatch) {
      activeIndex.value = String(exactMatch.id)      
      return
    }
    
    // 再尝试子菜单精确匹配
    for (const menu of menus.value) {
      if (menu.children) {
        const childMatch = menu.children.find(child => child.path === currentPath)
        if (childMatch) {
          activeIndex.value = String(childMatch.id)
          return
        }
      }
    }
    
   
    
    // 特殊处理：如果访问的是文章页，且没有匹配到任何菜单，则激活最近的匹配菜单
    if (currentPath.startsWith('/show')) {
      activeIndex.value = activeIndexBack 
      return
    }
  }
  // 如果 API 未加载完成或未匹配，使用 fallback 映射
  activeIndex.value = pathToIdMap[currentPath] || '1'

}

onMounted(async () => {
  try {
    const res: MenuResponse = await getMenus()
    if (res.data?.code == 0) {
      menus.value = res.data.data
    }
  } catch (error) {
    console.error('获取菜单数据失败:', error)
  }

  // 初始化 activeIndex
  updateActiveIndex()
})

// 监听路由变化，动态更新 activeIndex
watch(() => router.currentRoute.value.path, updateActiveIndex)
</script>

<style scoped>
.navbar-container {
  --primary-color: #409eff;
  --bg-color: #fff;
  --shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
}

.nav-row {
  padding: 0 20px;
  height: 60px;
  background: var(--bg-color);
  box-shadow: var(--shadow);
}

.logo-wrapper {
  height: 100%;
  display: flex;
  align-items: center;
}

.logo-img {
  height: 40px;
  transition: transform 0.3s ease;
}

.logo-img:hover {
  transform: scale(1.05);
}

.desktop-menu-wrapper {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.desktop-menu {
  border-bottom: none;
  height: 100%;
  display: inline-flex;
  --el-menu-base-level-padding: 0;
}

.desktop-menu :deep(.el-menu-item),
.desktop-menu :deep(.el-sub-menu__title) {
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 15px;
  transition: all 0.3s ease;
}

.desktop-menu :deep(.el-menu-item:hover),
.desktop-menu :deep(.el-sub-menu__title:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

.hamburger-wrapper {
  display: none;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  cursor: pointer;
  padding: 10px;
}

.hamburger-wrapper .el-icon {
  transition: all 0.3s ease;
}

.hamburger-wrapper .el-icon:hover {
  color: var(--primary-color);
  transform: scale(1.1);
}

.mobile-menu-container {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: var(--bg-color);
  box-shadow: var(--shadow);
  z-index: 1000;
}

.mobile-menu {
  border-right: none;
}

.mobile-menu :deep(.el-menu-item),
.mobile-menu :deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .desktop-menu-wrapper {
    display: none;
  }
  
  .hamburger-wrapper {
    display: flex;
  }
  
  .hamburger-wrapper .el-icon {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .nav-row {
    padding: 0 10px;
  }
  
  .logo-img {
    height: 32px;
  }
}
</style>
  
